package com.archerdu.demo.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.junit.Test;

public class IndexDemo {

    /**
     * 添加索引
     */
    @Test
    public void testAddIndex() {
        IndexDemo id = new IndexDemo();
        id.index(Constant.INDEX_PATH, Constant.DOC_PATH, true);
    }

    /**
     * 更新索引
     */
    @Test
    public void testUpdateIndex() {
        IndexDemo id = new IndexDemo();
        id.index(Constant.INDEX_PATH, Constant.DOC_PATH, false);
    }

    /**
     * 建立索引
     * 
     * @param indexPath
     * @param docPath
     * @param create
     */
    public void index(String indexPath, String docPath, boolean create) {
        try {
            Date start = new Date();
            File docDir = new File(docPath);

            // 存储目录
            Directory dir = FSDirectory.open(new File(indexPath));

            // 配置分析器
            Analyzer analyzer = new StandardAnalyzer(Constant.CURRENT_VERSION);
            IndexWriterConfig iwc = new IndexWriterConfig(Constant.CURRENT_VERSION, analyzer);
            if (create) {
                iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
            } else {
                iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
            }

            // 写入索引
            IndexWriter writer = new IndexWriter(dir, iwc);
            indexDocs(writer, docDir);

            writer.close();

            Date end = new Date();
            System.out.println((end.getTime() - start.getTime()) + " total milliseconds");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加文档
     * 
     * @param writer
     * @param file
     * @throws IOException
     */
    private void indexDocs(IndexWriter writer, File file) throws IOException {
        if (file.canRead()) {
            String[] files;
            int i;
            // 目录文件
            if (file.isDirectory()) {
                files = file.list();
                if (files != null)
                    for (i = 0; i < files.length; ++i)
                        indexDocs(writer, new File(file, files[i]));
            }
            // 单独文件
            else {
                FileInputStream fis;
                try {
                    fis = new FileInputStream(file);
                } catch (FileNotFoundException fnfe) {
                    return;
                }
                try {
                    // 文档（记录）
                    Document doc = new Document();

                    // 添加字段
                    Field pathField = new StringField(Constant.FIELD_ID, file.getPath(), Field.Store.YES);
                    doc.add(pathField);
                    doc.add(new LongField(Constant.FIELD_MODIFIED, file.lastModified(), Field.Store.YES));
                    doc.add(new TextField(Constant.FIELD_CONTENTS, new BufferedReader(new InputStreamReader(fis,
                            "UTF-8"))));

                    System.out.println(writer.getConfig().getOpenMode());
                    if (writer.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {
                        System.out.println("adding " + file);
                        writer.addDocument(doc);
                    } else {
                        System.out.println("updating " + file);
                        writer.updateDocument(new Term(Constant.FIELD_ID, file.getPath()), doc);
                    }
                } finally {
                    fis.close();
                }
            }
        }
    }
}
